﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports SL.Phone.Federation.Utilities
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.ViewModel
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.PivotContent
Imports Microsoft.Phone.Tasks
Imports System.IO.IsolatedStorage

Namespace Pages

    Partial Public Class MainPage
        Inherits PhoneApplicationPage
        
        Public Sub New()
            Me.InitializeComponent()

            Me.ViewModel = New MainPageViewModel()
            Me.LoadPivotItems()
			Me.OnMainPivotSelectionChanged()

			AddHandler Me.MainPivot.SelectionChanged, Sub(s, e) Me.OnMainPivotSelectionChanged()		
        End Sub

        Public Property ViewModel() As MainPageViewModel
            Get
                Return TryCast(Me.DataContext, MainPageViewModel)
            End Get
            Set(ByVal value As MainPageViewModel)
                Me.DataContext = value
            End Set
        End Property

        Protected Overrides Sub OnBackKeyPress(ByVal e As System.ComponentModel.CancelEventArgs)
            SetApplicationState("UserBackPress", True)
            MyBase.OnBackKeyPress(e)
        End Sub

        Private Shared Function GetIsolatedStorageSetting(Of T)(ByVal key As String) As T
            Dim isolatedStorage As IDictionary(Of String, Object) = IsolatedStorageSettings.ApplicationSettings
            If Not isolatedStorage.ContainsKey(key) Then
                Return Nothing
            End If

            Return CType(isolatedStorage(key), T)
        End Function

        Private Shared Sub RemoveIsolatedStorageSetting(ByVal key As String)
            Dim isolatedStorage As IDictionary(Of String, Object) = IsolatedStorageSettings.ApplicationSettings
            If isolatedStorage.ContainsKey(key) Then
                isolatedStorage.Remove(key)
            End If
        End Sub

        Private Shared Sub SetApplicationState(ByVal key As String, ByVal value As Object)
            If PhoneApplicationService.Current.State.ContainsKey(key) Then
                PhoneApplicationService.Current.State.Remove(key)
            End If

            PhoneApplicationService.Current.State.Add(key, value)
        End Sub

        Private Sub LoadPivotItems()
            Me.MainPivot.Items.Clear()
            Dim notificationsPage = New NotificationsPage()
            Dim notificationsPivot = New PivotItem()
            notificationsPivot.Header = "notifications"
            notificationsPivot.Name = "PushNotifications"
            notificationsPivot.Content = notificationsPage
            notificationsPage.ViewModel = Me.ViewModel.NotificationsViewModel
            AddHandler notificationsPage.BeginPushConnection, AddressOf Me.OnBeginPushConnection
            AddHandler notificationsPage.EndPushConnection, AddressOf Me.OnEndPushConnection
            Me.MainPivot.Items.Add(notificationsPivot)

            Dim tablesPage = New TablesPage()
            Dim tablesPivot = New PivotItem()
            tablesPivot.Header = "tables list"
            tablesPivot.Name = "TablesList"
            tablesPivot.Content = tablesPage
            tablesPage.ViewModel = Me.ViewModel.TablesPageViewModel
            Me.MainPivot.Items.Add(tablesPivot)

            Dim sampleDataTablesPage = New SampleDataTablePage()
            Dim sampleDataTablesPivot = New PivotItem()
            sampleDataTablesPivot.Header = "sample data"
            sampleDataTablesPivot.Name = "SampleDataRows"
            sampleDataTablesPivot.Content = sampleDataTablesPage
            sampleDataTablesPage.ViewModel = Me.ViewModel.SampleDataTablePageViewModel
            AddHandler sampleDataTablesPage.Navigate, AddressOf Me.OnNavigatePage
            Me.MainPivot.Items.Add(sampleDataTablesPivot)

            Dim listBlobsPage = New ListBlobsPage()
            Dim listBlobsPivot = New PivotItem()
            listBlobsPivot.Header = "list blobs"
            listBlobsPivot.Name = "ListBlobs"
            listBlobsPivot.Content = listBlobsPage
            listBlobsPage.ViewModel = Me.ViewModel.ListBlobsPageViewModel
            AddHandler listBlobsPage.TakePhoto, AddressOf Me.OnLaunchCamera
            Me.MainPivot.Items.Add(listBlobsPivot)

            Dim listQueuesPage = New ListQueuesPage()
            Dim listQueuesPivot = New PivotItem()
            listQueuesPivot.Header = "queues"
            listQueuesPivot.Name = "ListQueuesPage"
            listQueuesPivot.Content = listQueuesPage
            listQueuesPage.ViewModel = Me.ViewModel.ListQueuesPageViewModel
            AddHandler listQueuesPage.Navigate, AddressOf Me.OnNavigatePage
            Me.MainPivot.Items.Add(listQueuesPivot)

            Dim sqlSampleDataPage = New SqlSampleDataPage()
            Dim sqlSampleDataPivot = New PivotItem()
            sqlSampleDataPivot.Header = "sql azure data"
            sqlSampleDataPivot.Name = "SqlSampleData"
            sqlSampleDataPivot.Content = sqlSampleDataPage
            sqlSampleDataPage.ViewModel = Me.ViewModel.SqlSampleDataPageViewModel
            Me.MainPivot.Items.Add(sqlSampleDataPivot)
            Me.MainPivot.SelectedItem = notificationsPivot
        End Sub

        Private Function GetApplicationBarItemsByText(ByVal text As String) As IEnumerable(Of IApplicationBarMenuItem)
            Return Me.ApplicationBar.MenuItems.Cast(Of IApplicationBarMenuItem)().Where(Function(m) m.Text.Equals(text, StringComparison.OrdinalIgnoreCase)).Concat(Me.ApplicationBar.Buttons.Cast(Of IApplicationBarMenuItem)().Where(Function(b) b.Text.Equals(text, StringComparison.OrdinalIgnoreCase)))
        End Function

        Private Sub OnMainPivotSelectionChanged()
            Dim currentItem = TryCast(Me.MainPivot.SelectedItem, PivotItem)
            If currentItem IsNot Nothing Then
                Dim currentView = TryCast(currentItem.Content, UserControl)
                If currentView IsNot Nothing Then
                    Dim viewModel = TryCast(currentView.DataContext, PivotItemViewModel)
                    If viewModel IsNot Nothing Then
                        viewModel.UpdateApplicationBarButtons(Me.ApplicationBar, {"log out"})
                    End If
                End If
            End If
        End Sub

        Private Sub OnLaunchCamera(ByVal sender As Object, ByVal e As EventArgs)
            Dim cameraCaptureTask = New CameraCaptureTask()
            AddHandler cameraCaptureTask.Completed, AddressOf OnCameraCaptureTaskCompleted
            cameraCaptureTask.Show()
        End Sub

        Private Sub OnCameraCaptureTaskCompleted(ByVal sender As Object, ByVal e As PhotoResult)
            If e.TaskResult = TaskResult.OK Then
                SetApplicationState("PhotoResult", e)

                ' Delay navigation until the first navigated event.
                AddHandler Me.NavigationService.Navigated, AddressOf OnNavigatedCompleted
            End If
        End Sub

        Private Sub OnNavigatedCompleted(ByVal sender As Object, ByVal e As EventArgs)
            SetApplicationState("UserBackPress", False)

            ' Do the delayed navigation from the main page.
            Me.NavigationService.Navigate(New Uri("/Pages/UploadPhotoPage.xaml", UriKind.Relative))
            RemoveHandler Me.NavigationService.Navigated, AddressOf OnNavigatedCompleted
        End Sub

        Private Sub OnNavigatePage(ByVal sender As Object, ByVal e As NavigationEventArgs)
            Me.NavigationService.Navigate(e.Uri)
        End Sub

        Private Sub OnLogout(ByVal sender As Object, ByVal e As EventArgs)
            Me.MainPivot.IsEnabled = False
            Me.MainPivot.Opacity = 0.3R
            Me.LogOutStackPanel.Opacity = 1
            For Each button In Me.GetApplicationBarItemsByText("log out")
                button.IsEnabled = False
            Next button

            Dim pushNotificationClient = App.CloudClientFactory.ResolvePushNotificationClient()
            pushNotificationClient.Disconnect(Sub(r)
                                                  Me.Dispatcher.BeginInvoke(Sub()
                                                                                Me.CleanUp(r.Exception)
                                                                            End Sub)
                                              End Sub)
        End Sub

        Private Sub CleanUp(ByVal exception As Exception)
            If exception IsNot Nothing Then
                MessageBox.Show(exception.Message, "Push Unregistration Error", MessageBoxButton.OK)
            End If

            Me.MainPivot.IsEnabled = True
            Me.MainPivot.Opacity = 1
            Me.LogOutStackPanel.Opacity = 0

            For Each button In Me.GetApplicationBarItemsByText("log out")
                button.IsEnabled = True
            Next button

            ' Clean the current authentication token, flags and view models.
            App.CloudClientFactory.CleanAuthenticationToken()
            Me.DataContext = Nothing
            Me.MainPivot.Items.Clear()
            RemoveIsolatedStorageSetting("UserIsRegistered")
            SetApplicationState("UserBackPress", False)

            ' Navigate to the log in page.
            Me.NavigationService.GoBack()
        End Sub

        Private Sub OnBeginPushConnection(ByVal sender As Object, ByVal e As EventArgs)
            Dim items = Me.GetApplicationBarItemsByText("log out")
            For Each item In items
                item.IsEnabled = False
            Next item
        End Sub

        Private Sub OnEndPushConnection(ByVal sender As Object, ByVal e As EventArgs)
            Dim items = Me.GetApplicationBarItemsByText("log out")
            For Each item In items
                item.IsEnabled = True
            Next item
        End Sub
    End Class
End Namespace